// 导入插入数据库的函数
// 这里是注册的路由的执行函数
let { insertUsers, findUsers, findUsersId, updataUsersInfo } = require('../model/model')
let { findlist } = require('../model/mysql')
let { settoken } = require('../gather/token');
const { conn } = require('../gather/mongo');
exports.RegisterHandler = async (req, res) => {
   let { username, password } = req.body;
   // 在这里我们需要判断我们的数据库中是否有该用户名
   findUsers(username, (reslut) => {
      if (reslut.code === 0) return res.send({ code: 0, message: '服务器存在问题' })
      if (reslut.length !== 0) return res.send({ code: 0, message: '用户名存在~~~~' })
      // 代码运行到这里那么证明没有该用户名
      insertUsers({ username, password }, (reslut1) => {
         if (reslut1.serverStatus == 0) return res.send({ code: 0, message: '服务器存在问题' })
         res.send({ code: 200, message: '注册成功' })
      })
   })
}
// 这里是登录的路由执行函数
exports.LoginHandler = async (req, res) => {
   let { username, password } = req.body
   findUsers(username, (reslut) => {
      if (reslut.length === 0) return res.send({ code: 0, message: '用户名不存在~~~~' })
      if (username !== reslut[0].username || password !== reslut[0].password) return res.send({ code: 0, message: '用户名或者密码错误' })
      // 生成token
      let token = settoken({ id: reslut[0].id, nickname: reslut[0].nickname })
      // 将token存入数据库
      conn.query(`update user_info set token='${token}' where id=${reslut[0].id}`)
      res.send({
         code: 200,
         message: '登录成功',
         id: reslut[0].id,
         data: reslut[0],
         token
      })
   })
}
// 获取用户信息
exports.infoHandler = async (req, res) => {
   let { UserId } = req.body
   findUsersId(UserId, (reslut) => {
      if (reslut.length == 0) return res.send({ code: 0, message: '服务器存在问题' })
      res.send({
         code: 200,
         message: '成功获取用户信息',
         info: {
            id: reslut[0].id,
            username: reslut[0].username,
            nickname: reslut[0].nickname,
            roles: reslut[0].roles,
            age: reslut[0].age,
            sex: reslut[0].sex,
            phone: reslut[0].phone,
            signature: reslut[0].signature,
            allunread: reslut[0].allunread,
         }
      })
   })
}
// 修改用户信息
exports.updatainfoHandler = async (req, res) => {
   let data = req.body
   updataUsersInfo(data, (reslut) => {
      console.log(reslut);
      if (reslut.serverStatus != 2) return res.send({ code: 0, message: '服务器存在问题' })
      res.send({
         code: 200,
         message: '修改用户信息成功',
      })
   })
}
exports.findlistHandler = (req, res) => {
   findlist((aaaa) => {
      res.send({
         code: 200,
         message: '成功获取用户信息',
         msg: aaaa
      })
   })
}

exports.goPage = (req, res) => {
   res.send({
      code: 200,
      message: '登录状态',
   })
}


